import { createWriteStream, mkdtempSync } from 'fs'
import { sep, join } from 'path'
import { tmpdir } from 'os'
import { request } from 'urllib'
import { URL } from 'url'
export default function (url: string) {
    const u = new URL(url)
    const name = u.pathname.split('/').pop() || 'tmp'
    const tmppath = join(mkdtempSync(`${tmpdir()}${sep}`), name)
    return new Promise<string | false>(res => {
        const stream = createWriteStream(tmppath)
        stream.on('open', (fd) => {
            console.log('open')
            console.log(fd)
        })
        stream.on('pipe', (_src) => {
            _src.on('data', ()=> {
                console.log(stream.bytesWritten)
            })
            console.log('有数据正通过管道流入写入器');
        })
        stream.on('finish', () => {
            console.log('已经下载完成')
        })
        stream.on('error', function (err) {
            console.log(err)
        })
        stream.on('close', () => {
            console.log('cloes')
        })
        request(url, {
            writeStream: stream,
            timeout: 20 * 60 * 1000,
            beforeRequest: () => {
                console.log('开始下载')
            }
        }, (error, data) => {
            if (error) {
                console.log('下载失败')
                console.log(error)
                res(false)
            } else {
                res(tmppath)
            }
            console.log(error)
            console.log(data)
        })
    })
}